package com.qfedu.taskwebsocket.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/22 11:15
 * @Modified:
 */
@Slf4j
@Component
@Scope(scopeName = "prototype") //每一个连接都会创建一个对象 多例模式
@ServerEndpoint(value = "/server/{name}")
public class WebSocketServer {

    private static ConcurrentHashMap<String,Session> users=new ConcurrentHashMap();
    private String name;//记录当前在线的用户名
    /**
     * 1.连接服务器 监听
     * 活动连接信息*/
    @OnOpen
    public void open(Session session, @PathParam("name") String name) throws IOException {
        if(users.contains(name)){
            //昵称存在，不允许连接
            //单发消息
            session.getBasicRemote().sendText("亲，名称已存在！");
        }else{
            //可以
            users.put(name,session);
            this.name=name;
            //群发消息 欢迎词
            sendMoreMsg("欢迎"+name+"来到聊天室，鲜花送起来！",false);
        }
    }
    /**
     * 监听 接受消息*/
    @OnMessage
    public void receiveMsg(Session session,String msg) throws IOException {
        log.info("服务器接受消息，消息={}",msg);
        sendMoreMsg(name+"说："+msg,false);
    }
    /**
     * 监听 关闭连接*/
    @OnClose
    public void close(Session session) throws IOException {
        users.remove(name);
        sendMoreMsg(name+"离开了我们这个大家庭，让我们期待他下次再来！",false);
    }
    /**
     * 监听 异常*/
    @OnError
    public void error(Session session,Throwable throwable){
        throwable.printStackTrace();

    }
    /**
     * 群发 消息*/
    public static void sendMoreMsg(String msg,boolean self) throws IOException {
        for (String n:users.keySet()) {
            if(self){
                continue;
            }
            users.get(n).getBasicRemote().sendText(msg);
        }
    }

}
